package com.android.bbczw;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.android.bbczw.beans.AddressBean;
import com.android.bbczw.beans.AddressesBean;
import com.android.bbczw.beans.ContactBean;
import com.android.bbczw.beans.EmailBean;
import com.android.bbczw.beans.PhoneBean;
import com.android.bbczw.client.HttpClientMgr;
import com.android.bbczw.holder.AuthContextHolder;
import com.android.bbczw.utils.JSONParseUtils;

import android.app.ListActivity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.provider.Contacts.Phones;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class GetContactActivity extends ListActivity {
	
	private static final String TAG = "GetContactActivity.getData()";
	private Button uploadButton;
	private TextView message;

	@Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState); 
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        setContentView(R.layout.uploadcontact);
        message = (TextView) this.findViewById(R.id.upload_result);
        uploadButton = (Button)this.findViewById(R.id.upload_uploadbtn);
        OnClickListener listener = new OnClickListener (){
        	public void onClick(View paramView) {
        		getData();
        }};
        uploadButton.setOnClickListener(listener);
    }  
  
    private void getData() {  
    	message.setVisibility(0);
        List<ContactBean> contactList = new ArrayList<ContactBean>();
        Cursor cursor = null;
        try {
        	cursor = generateCursor(Phones.CONTENT_URI, null, null, null, null);
        }catch(Exception ex) {
        	System.out.println("get cursor failed! error[" + ex.toString() + "]");
        }
        if( null != cursor ) {
	        while(cursor.moveToNext()) { 
	        	//���ͨѶ¼��ÿ����ϵ�˵�ID
	        	ContactBean contactBean = new ContactBean();
	            String contactId = this.getContactInfo(cursor, ContactsContract.Contacts._ID);
	            Log.i(TAG, "contactId = ["+contactId+"]");
	            contactBean.setContactId(contactId);	           
	        	//���ͨѶ¼����ϵ�˵�����
	            String name = this.getContactInfo(cursor, ContactsContract.Contacts.DISPLAY_NAME);	 
	            Log.i(TAG, "name = ["+name+"]");
	            contactBean.setName(name);	
	            //����е绰�������ϵ�˵�ID���ҵ���ϵ�˵ĵ绰���绰�����Ƕ�� 	            
	            contactBean.setPhoneBean(getPhoneListInfo(contactId));   
	            //����email��ַ������emailҲ�����ж��
	           // contactBean.setEmailBean(getEmailListInfo(contactId));
	            //�����ϵ�˵ĵ�ַ 
	           // contactBean.setAddressesBean(getAddressListInfo(contactId));
	            contactList.add(contactBean);
	        }	       
	        cursor.close();
	    } 
        
        execute(contactList);
    }  
    
    private void execute(List<ContactBean> contactList) {
    	//�ϴ�����������
    	try {
	        String postParam = this.getString(R.string.server_url) + this.getString(R.string.upload_params); 
	        Boolean isSuccess = true;
	        for(ContactBean contactBean : contactList) {
	        	Map dataListMap = new HashMap();
		        dataListMap.put(this.getString(R.string.login_succ_oauthtoken), AuthContextHolder.get().getOauthtoken());
		        dataListMap.put(this.getString(R.string.login_succ_oauthtokensecret), AuthContextHolder.get().getOauthtokensecret());
		        dataListMap.put(this.getString(R.string.uploadcontact_param_token), this.getString(R.string.uploadcontact_param_token_value));
				for(Map.Entry<Integer, String> entry : contactBean.getPhoneBean().getPhones().entrySet()) {					
					dataListMap.put(this.getString(R.string.uploadcontact_param_contactid), contactBean.getContactId());
					dataListMap.put(this.getString(R.string.uploadcontact_param_name), contactBean.getName());
					dataListMap.put(this.getString(R.string.uploadcontact_param_type), entry.getKey().toString());
					dataListMap.put(this.getString(R.string.uploadcontact_param_phone), entry.getValue());
				}
				String response = HttpClientMgr.getInstance().execute(postParam, dataListMap, this.getString(R.string.server_chartype));				
				Log.i(TAG, "response = [" + response + "]");				
				if(response.equals("\"successful\"")) {
					continue;
				} else {
					isSuccess = false;
					break;
				}
	        }
	        
	        message.setVisibility(1);
	        if(isSuccess) {	        	
	        	message.setText(this.getString(R.string.uploadcontact_successmsg));
	        } else {
	        	message.setText(this.getString(R.string.uploadcontact_failedmsg));
	        }
        }
        catch(Exception ex) {
        	
        }
    }
    
    /**
     * ��ȡ�绰�б�
     * @param contactId
     * @return
     */
    private PhoneBean getPhoneListInfo(String contactId) {
    	PhoneBean phoneBean = new PhoneBean();
    	Map<Integer , String> phoneMap = new HashMap<Integer , String>();
    	Cursor phoneCursor = generateCursor(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
    	while (phoneCursor.moveToNext()) {    		
    		String phone = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));    	
    		int type = phoneCursor.getInt(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));    		
    		phoneMap.put(type, phone.replaceAll("-", ""));
    		Log.i(TAG, "phone = ["+phone.replaceAll("-", "")+"]");
    		Log.i(TAG, "type = ["+type+"]");    		  		
    	}
    	phoneCursor.close();
    	phoneBean.setPhones(phoneMap);
    	return phoneBean;
    }
    
    /**
     * ��ȡEmail�б�
     * @param contactId
     */
    private EmailBean getEmailListInfo(String contactId) {
    	EmailBean emailBean = new EmailBean();
    	List<Map<Integer, String>> emails = new ArrayList<Map<Integer, String>>();
    	Cursor emailCursor = generateCursor(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
    	while (emailCursor.moveToNext()) {    		
    		String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
    		int type = emailCursor.getInt(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
    		Map<Integer , String> emailMap = new HashMap<Integer , String>();
    		emailMap.put(type, email);
    		Log.i(TAG, "email = ["+email+"]");
    		Log.i(TAG, "type = ["+type+"]");
    		emails.add(emailMap);    		
    	}
    	emailCursor.close();
    	emailBean.setEmails(emails);
    	return emailBean;
    }
    
    /**
     * ��ȡ��ϸ��ַ�б�
     * @param contactId
     * @return
     */
    private AddressesBean getAddressListInfo(String contactId) {
    	AddressesBean addressesBean = new AddressesBean();
    	List<AddressBean> addresses = new ArrayList<AddressBean>();
    	Cursor addressesCursor = generateCursor(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
                null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
    	while (addressesCursor.moveToNext()) {   
    		AddressBean addressBean = new AddressBean();
    		String address = addressesCursor.getString(addressesCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS ));
    		String pobox = addressesCursor.getString(addressesCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
    		String street = addressesCursor.getString(addressesCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
    		String city = addressesCursor.getString(addressesCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));   		
    		String region = addressesCursor.getString(addressesCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
    		String postcode = addressesCursor.getString(addressesCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
    		String country = addressesCursor.getString(addressesCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
    		String type = addressesCursor.getString(addressesCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
    		Log.i(TAG, "address = ["+address+"]");
    		Log.i(TAG, "pobox = ["+pobox+"]");
    		Log.i(TAG, "street = ["+street+"]");
    		Log.i(TAG, "city = ["+city+"]");
    		Log.i(TAG, "region = ["+region+"]");
    		Log.i(TAG, "postcode = ["+postcode+"]");
    		Log.i(TAG, "country = ["+country+"]");
    		Log.i(TAG, "type = ["+type+"]");
    		addressBean.setAddress(address);
    		addressBean.setPobox(pobox);
    		addressBean.setStreet(street);
    		addressBean.setCity(city);
    		addressBean.setRegion(region);
    		addressBean.setPostcode(postcode);
    		addressBean.setCountry(country);
    		addressBean.setType(type);
    		addresses.add(addressBean);
    	}
    	addressesCursor.close();
    	addressesBean.setAddresses(addresses);
    	
    	return addressesBean;
    }
    
    /**
     * ���ͨѶ¼��ÿ����ϵ�˵���Ϣ
     * @param cursor
     * @return
     */
    private String getContactInfo(Cursor cursor, String type) {
    	return  cursor.getString(cursor.getColumnIndex(type));
    }
    
    private Cursor generateCursor(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {    	
    	return getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
    }
}